package com.usian.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.common.exception.CatchCustomException;
import com.usian.common.exception.code.UserStatusCode;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.behavior.dtos.FollowBehaviorDto;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.dtos.UserRelationDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.model.user.pojos.ApUserFan;
import com.usian.model.user.pojos.ApUserFollow;
import com.usian.user.feign.ArticleFeign;
import com.usian.user.mapper.ApUserFanMapper;
import com.usian.user.mapper.ApUserFollowMapper;
import com.usian.user.mapper.ApUserMapper;
import com.usian.user.service.ApUserRelationService;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@SuppressWarnings("ALL")
@Transactional
public class ApUserRelationServiceImpl implements ApUserRelationService {

    @Autowired
    private ApUserFollowMapper apUserFollowMapper;

    @Autowired
    private ApUserFanMapper apUserFanMapper;

    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private ApUserMapper apUserMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //1.参数检查  关注与取消关注
        if(dto.getOperation() == null || dto.getOperation()<0 || dto.getOperation() > 1){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"关注方式出现问题");
        }
        // 关联的作者id
        if(dto.getAuthorId() == null){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"作者Id不能为空");
        }
        //1. 根据作者Id先查询作者信息 判断作者信息是否为空 如果为空证明有问题
        ApAuthor apAuthor =  articleFeign.findById(dto.getAuthorId());
        if(apAuthor==null){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"需要关注的作者不存在");
        }
        Integer id = AppThreadLocalUtils.getUser().getId();
        ApUser apUser1 = apUserMapper.selectById(id);
        AppThreadLocalUtils.setUser(apUser1);
        // 被关注的 作者权限的账号的Id
        Integer followId = apAuthor.getUserId();
        // 获取当前登录用户（需要关注或者取消关注的当前登录的账号Id）
        ApUser apUser = AppThreadLocalUtils.getUser();
        if(apUser ==null){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"当前用户没有登录");
        }else{
            if(apUser.getId()==0){
                CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"当前用户没有登录");
            }
        }
        // 用户登录了
        if(dto.getOperation() == 0){
            // 用户关注
            followByUserId(apUser,followId,dto.getArticleId());
        }else if(dto.getOperation() == 1){
            // 用户取消关注
            followCancelByUserId(apUser,followId);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    // 关注
    private void followByUserId(ApUser apUser,Integer followId,Long articleId){
        //判断用户是否已经关注过了  如果关注提示 如果没有关注才开始保存  保存需要保存两张表  粉丝表  关注表
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getUserId, apUser.getId())
                .eq(ApUserFollow::getFollowId, followId));
        if(apUserFollow == null){
            //保存关注信息
            apUserFollow = new ApUserFollow();
            apUserFollow.setFollowName(apUser.getName());
            apUserFollow.setLevel((short)0);
            apUserFollow.setIsNotice(true);
            apUserFollow.setCreatedTime(new Date());
            apUserFollow.setUserId(apUser.getId());
            apUserFollow.setFollowId(followId);
            apUserFollowMapper.insert(apUserFollow);
            //保存数据  ap_user_follow   ap_user_fan
            ApUserFan apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery()
                    .eq(ApUserFan::getUserId, followId)
                    .eq(ApUserFan::getFansId, apUser.getId()));
            if(apUserFan==null){
                apUserFan = new ApUserFan();
                apUserFan.setUserId(followId);
                apUserFan.setFansId(apUser.getId().longValue());
                apUserFan.setFansName(apUser.getName());
                apUserFan.setLevel((short)0);
                apUserFan.setIsDisplay(true);
                apUserFan.setIsShieldLetter(false);
                apUserFan.setIsShieldComment(false);
                apUserFan.setCreatedTime(new Date());
                apUserFanMapper.insert(apUserFan);
            }
            // 发送MQ 交换机类型：dricter 队列模式 roukingkey  消息： JSON格式String类型数据
            FollowBehaviorDto dto = new FollowBehaviorDto();
            dto.setFollowId(followId); // 关注Id
            dto.setArticleId(articleId); //文章Id
            dto.setUserId(apUser.getId()); // 获取行为实体
            rabbitTemplate.convertAndSend("BehaviorExchanges","behavior", JSON.toJSONString(dto));
       }else{
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"已经关注");
        }
    }

    // 取消关注
    /**
     *
     * @param apUser 当前登录用户Id
     * @param followId 被关注的ID（作者账号的userId）
     */
    private void followCancelByUserId(ApUser apUser,Integer followId){
        //先查询有没有关系
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getUserId, apUser.getId())
                .eq(ApUserFollow::getFollowId, followId));
        if(apUserFollow == null){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"没有关注");
        }else{
            //删除用户粉丝信息 查询粉丝信息
            ApUserFan apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery()
                    .eq(ApUserFan::getUserId, followId)
                    .eq(ApUserFan::getFansId, apUser.getId()));
            if(apUserFan!=null){
                //删除
                apUserFanMapper.delete(Wrappers.<ApUserFan>lambdaQuery()
                        .eq(ApUserFan::getUserId, followId)
                        .eq(ApUserFan::getFansId, apUser.getId()));
            }

            //删除用户关注信息
            apUserFollowMapper.delete(Wrappers.<ApUserFollow>lambdaQuery()
                    .eq(ApUserFollow::getUserId, apUser.getId())
                    .eq(ApUserFollow::getFollowId, followId));
        }
    }

}
